package com.sdlight.snowflake.controller;

import com.sankuai.inf.leaf.common.Result;
import com.sankuai.inf.leaf.common.Status;
import com.sdlight.snowflake.dto.ApiRespBase;
import com.sdlight.snowflake.service.SnowflakeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lihaitao
 */
@RestController
public class IdController {

    /**
     * 允许一次生成的最大数量限制.
     */
    private static final int MAX_COUNT = 10000;

    @Autowired
    SnowflakeService snowflakeService;

    @GetMapping("/id/get")
    public ApiRespBase getId() {
        Result result = snowflakeService.getId("");
        if (result.getStatus().equals(Status.EXCEPTION)) {
            return ApiRespBase.fail(result.toString());
        }
        return ApiRespBase.success(String.valueOf(result.getId()));
    }

    @GetMapping("/id/batch")
    public ApiRespBase batch(@RequestParam(required = false, defaultValue = "1") int count) {
        List<String> list = new ArrayList<>(1);
        int maxCount = count > MAX_COUNT ? MAX_COUNT : count;
        int index = 0;
        do {
            try {
                Result result = snowflakeService.getId("");
                if (result.getStatus().equals(Status.EXCEPTION)) {
                    continue;
                }
                list.add(String.valueOf(result.getId()));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            index++;
        } while (index < maxCount);
        return ApiRespBase.success(list);
    }
}
